var http = require('http');
//var request = require('request');
var qs = require('querystring');
var serverconf = require('../conf/serverconf');
//var iconv = require('iconv-lite');
//var encoding = require('encoding');

module.exports = {
    sendPostData: function(param, callback) {
        var content = qs.stringify(param.content);
        var options = {
            hostname: serverconf.conf.hostname,
            port: serverconf.conf.port,
            path: param.url,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                "Content-Length": content.length
            }
        };

        var req = http.request(options, function(res) {
            console.log('STATUS: ' + res.statusCode);
            //   console.log('HEADERS: ' + JSON.stringify(res.headers));  
            res.setEncoding('utf8');
            res.on('data', function(result) {
                if(callback) {
                    console.info(result);
                    result=unescape(result.replace(/\\u/g, '%u'));
                    // result=result.replace(/\r\n/g,'');
                    // result=result.replace('操作成功','');
                    if(result.indexOf('{') !== 0) {
                        console.info('前面有东西');
                        result = result.substring(1, result.length);
                    }
                    console.info(result.length);
                    //result=result.replace('message:\u64cd\u4f5c\u6210\u529f,','');
                    //result=iconv.decode(result, 'gbk');

                    //result = encoding.convert(result, 'UTF-8');
                    callback(null, result);
                }
            });
        });

        req.on('error', function(e) {
            console.log('problem with request: ' + e.message);
            if(callback) {
                callback(e.message, null);
            }
        });

        //write data to request body  

        console.info('content:' + content);
        req.write(content);

        req.end();
    }
};